<template>
  <div>
    <div style="border-radius: 20px;width: 780px;height: 470px;overflow: hidden">
      <!-- 地图容器 -->
      <div id='worldMap' class="map" :style="{
        width:'780px',
        height:'470px',
        borderRadius: '20px'
      }"></div>
    </div>
    <button class="button" v-show='mapHistory.length' @click='back'> 返回</button>

  </div>
</template>

<script>
import axios from 'axios'
import * as echarts from "echarts";
import {chinaProvince, worldAdcode, worldMapName} from "@/helper/worldMapName"
import {cityMap} from "@/helper/china-main-city-map";
import {cityMap2} from "@/helper/china-main-city-map2";
import {getReportByAreaCode, listReportByAreaCode} from "@/api/res";
import {mapMutations, mapState} from "vuex";

export default {
  name: "MapView",
  data() {
    return {
      mapHistory: []
    }
  },
  computed: {
    ...mapState(['show', 'settings'])
  },
  created() {
    this.getWorldJson()
  },
  methods: {
    ...mapMutations(['addReport', 'setActive', 'setLoading', 'setMapLoading']),
    getHeight() {
      this.height = window.innerHeight - 70 + 'px';
    },
    /**
     * domId: 地图容器ID
     * mapName: 地图名称
     * mapJson: 地图数据
     * zoom: 地图放大倍数
     * mapCenter: 当前视角的中心点，用经纬度表示
     */
    worldMap(domId, mapName, mapJson, zoom, mapCenter) {
      //初始化echarts实例
      let myChart = echarts.init(document.getElementById(domId));
      //注册地图
      echarts.registerMap(mapName, mapJson);  // mapName 如果不是china南海诸岛不会显示
      myChart.off('click') // 解绑事件处理函数。为了解决地图下钻会重复触发点击事件的问题
      // 单独给中国的省份加上渐变背景
      // 单独给中国的省份设置label颜色或者区域颜色
      let mapRegions = []

      //中国省份label
      let cityLabelColor = {
        normal: {
          show: true,
          color: 'rgba(0,0,0,0.3)'
        },
        emphasis: {
          show: true,
          color: 'rgba(0,0,0,0.3)'
        },
      }

      //中国省份区域颜色
      let cityItemStyle = {
        normal: {
          borderColor: 'rgb(250,250,253)',
          borderWidth: 1,
          areaColor: {
            type: 'radial',
            x: 0.5,
            y: 0.5,
            r: 0.8,
            colorStops: [{
              offset: 0,
              color: 'rgba(74,130,205,0.1)' // 0% 处的颜色
            }, {
              offset: 1,
              color: 'rgba(72,131,217,0.2)' // 100% 处的颜色
            }],
            globalCoord: false // 缺省为 false
          },
          shadowColor: 'rgba(7,5,5,0.3)',
          shadowOffsetX: -2,
          shadowOffsetY: 2,
          shadowBlur: 10
        },

        emphasis: {
          areaColor: '#7091d6',
          borderWidth: 0
        }
      }

      chinaProvince.forEach(function (item, index) {
        let obj = {
          name: item,
          label: cityLabelColor,
          itemStyle: cityItemStyle,
          tooltip: {
            trigger: 'item',
            backgroundColor: 'rgba(255,255,255,0.8)',//通过设置rgba调节背景颜色与透明度
            // formatter: '{a}'
          },
        }
        mapRegions.push(obj, {
          name: '南海诸岛',
          label: cityLabelColor,
          itemStyle: cityItemStyle,
        })
      })

      let foreignColor = {
        areaColor: {
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [{
            offset: 0,
            color: '#ebedff' // 0% 处的颜色
          }, {
            offset: 1,
            color: '#d4d6e3' // 100% 处的颜色
          }],
        },
        borderColor: '#b2b3bf',
        borderWidth: 1,
      }

      let option = {
        tooltip: {
          trigger: 'item',
        },
        style: {
          borderColor: "20px"
        },
        geo: {
          show: true,
          map: mapName,
          // nameMap: worldMapName,
          label: {
            normal: {
              color: 'rgba(0,0,0,.3)',
              show: true,
            },
            emphasis: {
              color: 'rgba(0,0,0,.3)',
              show: true,
            }
          },
          zoom: zoom,
          center: mapCenter, // 地图中心点,用于初始化的时候中国在视角中心
          roam: true,
          itemStyle: {
            normal: foreignColor,
            emphasis: foreignColor
          },
          regions: mapRegions
        }

      }

      //使用制定的配置项和数据显示图表
      myChart.setOption(option, true);

      // 监听地图的点击事件
      myChart.on('click', async (mdata) => {

        if (this.show) {
          return
        }
        // console.log("=====加载中=====")
        this.setLoading(true);
        let now = new Date();
        let adcode = cityMap2[mdata.name]

        if (adcode) {
          getReportByAreaCode(adcode).then(res1 => {
            if (res1.code === 10000) {
              listReportByAreaCode(adcode).then(res2 => {
                this.addReport({
                  ...res1.data,
                  "searchTime": now.toLocaleDateString().replaceAll('/', '-')
                      + '  '
                      + now.toTimeString().substring(0, 8),
                  "allInfo": res2.data
                })

              })
            } else {
              this.setActive(null)
            }
            // console.log("=====加载完毕=====")
            this.setLoading(false);
          })
        } else {
          // 如果不是中国地图，则查找全球地图
          console.log(mdata)
          let worldMapKey = Object.keys(worldAdcode)
          let len = worldMapKey.length;

          for (let i = 0; i < len; i++) {
            //如果字符串中不包含目标字符会返回-1
            if (worldMapKey[i].indexOf(mdata.name) >= 0) {
              adcode = worldAdcode[worldMapKey[i]];
              break
            }
          }
          if (adcode) {
            getReportByAreaCode(parseInt(adcode)).then(res => {
              if (res.code === 10000) {
                this.addReport({
                  ...res.data,
                  "searchTime": now.toLocaleDateString().replaceAll('/', '-')
                      + '  '
                      + now.toTimeString().substring(0, 8)
                })
              }
            })
          } else {
            this.setActive(null)
          }
          // console.log("=====加载完毕=====")
          this.setLoading(false);
        }

        // 若没开启可查看省份地图，则return
        if (!this.settings.switchSetting.provinceMap.value) {
          return;
        }
        let cityName = "";
        let cityMapKey = Object.keys(cityMap)
        // 检查点击的地图区域是不是中国的如果不是就return
        let flag = cityMapKey.some(item => item === mdata.name)
        if (!flag) return;
        this.mapHistory.push(mdata.name)
        cityName = mdata.name
        let {data: cityMapJson} = await axios.get(`/map-json/city-map/${cityMap[cityName]}.json`)
        this.worldMap('worldMap', 'city', cityMapJson, null, null)
      })
    },

    async getWorldJson() {
      let {data: WorldMapJson} = await axios.get('/map-json/word-china.json')
      this.worldMap('worldMap', 'china', WorldMapJson, 6, [104, 35])
      this.setMapLoading(false);
    },

    async back() {
      this.setMapLoading(true);
      this.mapHistory.pop()
      if (this.mapHistory.length < 1) {
        this.getWorldJson()
      } else {
        let historyCityName = this.mapHistory[this.mapHistory.length - 1]
        let {data: cityMapJson} = await axios.get(`/map-json/city-map/${cityMap[historyCityName]}.json`)
        this.worldMap('worldMap', 'city', cityMapJson, null, null)
      }
    }
  },
  mounted() {
    document.addEventListener("touchstart", function () {
    }, true)
  }
}
</script>

<style lang="less">

.active-name {
  font-weight: 400;
  size: 10px;
  height: 10px;
}

.button {
  width: 100px;
  height: 30px;
  margin: 10px;
  border: 0 none;
  background: var(--background-button-color);
  box-shadow: var(--box-shadow);
  border-radius: var(--border-radius);
  cursor: pointer;
}

.button:hover {
  transition: all 150ms linear;
  background-color: var(--hover-background-color);
  opacity: 0.85;
}

.button:active {
  transition: all 150ms linear;
  opacity: 0.75;
}

.button:focus {
  outline-offset: -4px;
}

</style>